#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int wfd)
{
    char buffer[1024] = {0};
    int cnt = 0;
    while(true)
    {
        cnt++;
        snprintf(buffer, sizeof(buffer), "I am child, my pid:%d, cnt:%d", getpid(), cnt);
        write(wfd, buffer, strlen(buffer));
        //write(wfd, "0", 1);
        //printf("%d\n", cnt);
        sleep(1);
    }
}

void ParentRead(int rfd)
{
    char buffer[1024] = {0};
    while(true)
    {
        //sleep(100);
        size_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say:" << buffer << std::endl;
        }
    }
}

int main()
{
    //创建管道
    int fd[2] = {0};
    int st = pipe(fd);
    if(st < 0)
    {
        std::cerr << "pipe" << std::endl;
    }
    //std::cout << fd[0] << std::endl;
    //std::cout << fd[1] << std::endl;

    //创建子进程，并实现单向通信 -- 子进程写，父进程读
    pid_t id = fork();
    if(id == 0)//子进程
    {
        close(fd[0]);
        ChildWrite(fd[1]);
        close(fd[1]);
        exit(0);
    }
    else
    {
        close(fd[1]);
        ParentRead(fd[0]);
        close(fd[0]);
        waitpid(id, nullptr, 0);
    }
    return 0;
}